package com.example.kotlindemo.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.kotlindemo.R
import com.example.kotlindemo.data.Task
import java.text.SimpleDateFormat
import java.util.Locale


class PendingTaskAdapter(
    private val onCheckClicked: (Task) -> Unit,
    private val onEditClicked: (Task) -> Unit
) : ListAdapter<Task, PendingTaskAdapter.PendingTaskViewHolder>(TaskDiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PendingTaskViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_pending_task, parent, false)
        return PendingTaskViewHolder(view, onCheckClicked, onEditClicked)
    }

    override fun onBindViewHolder(holder: PendingTaskViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    class PendingTaskViewHolder(
        itemView: View,
        private val onCheckClicked: (Task) -> Unit,
        private val onEditClicked: (Task) -> Unit
    ) : RecyclerView.ViewHolder(itemView) {

        private val taskNameTextView: TextView = itemView.findViewById(R.id.tvTaskNamePending)
        private val createTimeTextView: TextView = itemView.findViewById(R.id.tvCreateTimePending)
        private val checkmarkImageView: ImageView = itemView.findViewById(R.id.ivCheckmarkPending)
        private val editImageView: ImageView = itemView.findViewById(R.id.ivEditTask)
        private var currentTask: Task? = null
        private val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())

        init {
            checkmarkImageView.setOnClickListener {
                currentTask?.let { onCheckClicked(it) }
            }
            editImageView.setOnClickListener {
                currentTask?.let { onEditClicked(it) }
                // 可以在这里触发编辑逻辑，例如弹出一个对话框
            }
            // itemView.setOnClickListener { /* 如果需要点击整个 item 的事件 */ }
        }

        fun bind(task: Task) {
            currentTask = task
            taskNameTextView.text = task.name
            createTimeTextView.text = task.createdTimestamp.let { dateFormat.format(it) }
        }
    }
}